import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

var car = JSON.parse(localStorage.getItem('car') || '[]');
const state = {
    car: car
}
const mutations = {
    addtocar(state, goods) {
        console.log(goods, 123);
        var flag = false; //假设车里没有相同的商品

        state.car.some(item => {
            if (item.id === goods.id) {
                item.count += parseInt(goods.count)

                flag = true
                return true //some默认返回ture
            }
        });
        console.log(state.car, 1213);
        if (flag == false) {
            state.car.push(goods)
                // console.log(state.car, 1111111);
        };
        localStorage.setItem('car', JSON.stringify(state.car))
    },
    /* 修改购物车中的商品数量 */
    updateinfo(state, goodsinfo) {
        // console.log(goodsinfo, 1231);
        state.car.some(item => {
            if (item.id === goodsinfo.id) {
                item.count = parseInt(goodsinfo.count)
                return true
            }
        })
        localStorage.setItem('car', JSON.stringify(state.car))
    },
    /* 根据id进行删除商品 */
    delcar(state, id) {
        state.car.some((item, i) => {
            if (item.id === id) {
                state.car.splice(i, 1)
                return true
            }
        });
        localStorage.setItem('car', JSON.stringify(state.car))
    },
    updategoods(state, info) {
        state.car.some((item, i) => {
            if (item.id == info.id) {
                item.selected = info.selected
                return true
            }
        })
        localStorage.setItem('car', JSON.stringify(state.car))
    }

}
const getters = {
    getall(state) {
        var c = 0;
        state.car.forEach(item => {
            c += item.count
        })
        return c
    },
    getgoodscount(state) {
        var p = {}
        state.car.forEach(item => {
            p[item.id] = item.count
        })
        return p;
    },
    getselect(state) {
        var o = {}
        state.car.forEach(item => {
            o[item.id] = item.selected
        });
        return o
    },
    getamount(state) {
        var o = {
            count: 0,
            amount: 0
        };
        state, car.forEach(item => {
            if (item.selected) {
                o.count += item.count;
                o.amount += item.count * item.price;
            }
        })
        return o;
    }
}

export default new Vuex.Store({
    state,
    getters,
    mutations
})